package com.hitqz.robot.biz.service.impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hitqz.robot.api.common.entity.PatrolDev;
import com.hitqz.robot.biz.mapper.PatrolDevMapper;
import com.hitqz.robot.biz.service.PatrolDevService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author wengyx
 * @date 2024/8/7
 */
@Service
@AllArgsConstructor
public class PatrolDevServiceIml extends ServiceImpl<PatrolDevMapper, PatrolDev> implements PatrolDevService {
    @Override
    public List<Tree<Long>> selectTree() {
        //查询所有设备
        List<PatrolDev> list = list();
        if (list.isEmpty()){
            PatrolDev patrolDev = new PatrolDev();
            patrolDev.setName("默认节点");
            patrolDev.setParentId(0);
            patrolDev.setIsParent(1);
            save(patrolDev);
        }
        //按parentId进行分组
        Map<Integer, List<PatrolDev>> map = list.stream().collect(Collectors.groupingBy(PatrolDev::getParentId));
        List<TreeNode<Long>> collect = list.stream()
                .filter(dev-> Objects.equals(dev.getIsParent(),1)).map(dev -> {
                    TreeNode<Long> treeNode = new TreeNode();
                    treeNode.setId(dev.getId());
                    treeNode.setParentId(0L);
                    treeNode.setName(dev.getName());
                    treeNode.setWeight(dev.getId());
                    Map<String, Object> extra = new HashMap<>(8);
                    List<PatrolDev> patrolDevs = Optional.ofNullable(map.get(dev.getId().intValue())).orElse(new ArrayList<>());
                    List<TreeNode<Long>> childrenNode = patrolDevs.stream().map(f -> {
                                TreeNode<Long> children = new TreeNode();
                                children.setId(f.getId());
                                children.setParentId((long)f.getParentId());
                                children.setName(f.getName());
                                children.setWeight(f.getId());
                                return children;
                            }
                    ).collect(Collectors.toList());
                    extra.put("children", childrenNode);
                    treeNode.setExtra(extra);
                    return treeNode;
                })
                .collect(Collectors.toList());

        return TreeUtil.build(collect, 0L);
    }
}
